import { defineStore } from "pinia";
import router from "@/router";
class foldMenuState {
  menus = [];
  defaultActive = "";
  collapse = false;
  cached = [];
}
export const useFoldMenuStore = defineStore("foldMenu", {
  state: () => new foldMenuState(),
  actions: {
    setMenus(menus) {
      this.menus = menus;
    },
    setDefaultActive(path) {
      this.defaultActive = path;
    },
    setCollapse(collapse) {
      this.collapse = collapse;
    },
    addCache(tag) {
      if (this.cached.some((ele) => ele.name === tag.name)) return;
      this.cached.push(tag);
    },
    removeCache(tag) {
      let index = this.cached.findIndex((ele) => ele.name === tag.name);
      if (index !== -1) {
        this.cached.splice(index, 1);
        if (this.cached.length === 0) {
          return router.push("/dashboard");
        }
        // 关闭掉的不是自己
        if (router.currentRoute.value.name !== tag.name) return;
        // 接着路由导向到前一个或者后一个
        let nextTag = this.cached[index - 1] || this.cached[index];
        nextTag && router.push(nextTag);
      }
    },
  },
});
